package com.ctsi.framework.freemarker.support;

import freemarker.ext.beans.BeansWrapper;
import freemarker.ext.beans.BeansWrapperBuilder;
import freemarker.template.TemplateHashModel;
import freemarker.template.TemplateModelException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.ui.freemarker.FreeMarkerConfigurationFactory;

import javax.annotation.PostConstruct;
import java.util.Optional;

@Configuration
@ConditionalOnClass({ freemarker.template.Configuration.class,
        FreeMarkerConfigurationFactory.class })
@AutoConfigureAfter(FreeMarkerAutoConfiguration.class)
@EnableConfigurationProperties(SharedVariable.class)
public class FreeMarkerAutoConfig {

    private static final Logger log = LoggerFactory.getLogger(FreeMarkerAutoConfig.class);

    @Autowired
    private freemarker.template.Configuration configuration;
    @Autowired
    private org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver freeMarkerViewResolver;
    @Autowired
    private org.springframework.web.servlet.view.InternalResourceViewResolver internalResourceViewResolver;

    @Autowired
    private SharedVariable sharedVariable;


    @PostConstruct
    public void initFreeMarker(){
        configuration.setDateFormat("yyyy-MM-dd");
        configuration.setDateTimeFormat("yyyy-MM-dd HH:mm:ss");
        log.debug("load freemarker setting : {}",sharedVariable.getSharedVariable());
        BeansWrapper wrapper =(new BeansWrapperBuilder(freemarker.template.Configuration.getVersion())).build();
        TemplateHashModel staticModels = wrapper.getStaticModels();

        Optional.of(sharedVariable.getSharedVariable()).ifPresent(var -> {
            var.entrySet().forEach(en ->{
                try {
                    configuration.setSharedVariable(en.getKey(),staticModels.get(en.getValue()));
                } catch (TemplateModelException e) {
                    log.error("setting freemarker SharedVariable ocurred error: {}",e);
                }
            });
        });

    }


}
